package com.umbacos.udm.client.presenter.popup;

import java.util.Iterator;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.Response;
import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.CheckBox;
import com.google.gwt.user.client.ui.DockPanel;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.HasVerticalAlignment;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.umbacos.udm.client.arch.Popup;
import com.umbacos.udm.client.arch.Table;
import com.umbacos.udm.client.arch.Util;
import com.umbacos.udm.client.model.AsyncComm;
import com.umbacos.udm.client.model.UdmStatus;
import com.umbacos.udm.client.view.TorrentPopupView;

public class TorrentPopupPresenter {

	private final static int CM_PLAY=0;
	private final static int CM_META=1;

	private String rootFile;
	
	final private TorrentPopupView tv=new TorrentPopupView();
	final private UdmStatus udmStatus;
	
	public TorrentPopupPresenter(UdmStatus udmStatus){
		this.udmStatus=udmStatus;
	}
	
	public void loadAndBind(final int command, final String file){
		rootFile=file;
		AsyncComm ac = new AsyncComm();
		ac.addPostData("file", file);
		ac.send(AsyncComm.META, new RequestCallback() {
			
			@Override
			public void onResponseReceived(Request request, Response response) {
				bind(command, response.getText());
			}
			
			@Override
			public void onError(Request request, Throwable exception) {
				Popup pp = new Popup("Status Update", new HTML(exception.getMessage()), Popup.POPUP_CLOSE);
				pp.showPopup();
			}
		});

	}
	
	public void bind(int command, final String response){

		switch (command) {
		case CM_PLAY:tv.setText("Start Torrent");break;
		case CM_META:tv.setText("Properties");break;
		}
		
		JSONObject jo = new JSONObject( AsyncComm.JSON(response));

		// Titolo
		tv.ftMain.setWidget(0, 0, tv.imIcon);
		tv.ftMain.setText(0, 1, jo.get("file").toString());

		JSONObject benc=jo.get("benc").isObject();

		if (command==CM_META) {			
			// Varie info
			for (Iterator<String> it=benc.keySet().iterator(); it.hasNext();) {
				String key=it.next();
				if ((key.compareTo("info")!=0) && (key.compareTo("creation date")!=0))
					insertKeyRow(key, benc);			
			}
	
			String key="creation date"; 
			if (benc.containsKey(key)) 
				insertRow(key, Util.JSONEpocDateFormat(key, benc));
		}
		
		// Main info
		JSONObject info=benc.get("info").isObject();
		insertKeyRow("name", info);
		insertRow("piece length", Util.JSONNumberFormat("piece length", info));

		int width=Window.getClientWidth();
		
		tv.ftMain.setWidth(width*0.4 + "px");
		tv.ftFiles.setWidth("100%");
		tv.vpMain.add(tv.ftMain);
		
		// File list
		if (info.containsKey("files")) {
			JSONArray files = info.get("files").isArray();
			for (int j = 0; j < files.size(); ++j) {
				JSONObject f = files.get(j).isObject();
				String l=Util.JSONNumberFormat("length", f);
				String p=f.get("path").isArray().get(0).toString();
				if (command==CM_PLAY) {
					CheckBox ck=new CheckBox();
					ck.setValue(true);
					tv.ftFiles.setWidget(j, 0, ck);
				}
				tv.ftFiles.setText(j, 1, p);
				tv.ftFiles.setText(j, 2, l);
				tv.ftFiles.getCellFormatter().addStyleName(j, 2, "alignright");
			}

			if (files.size()>10) {
				tv.spFiles.add(tv.ftFiles);
				tv.spFiles.setHeight("200px");
				tv.spFiles.setStyleName("tableborder");
				tv.vpMain.add(tv.spFiles);
			} else {
				tv.ftFiles.setStyleName("tableborder");
				tv.vpMain.add(tv.ftFiles);				
			}
		}

		// Buttons
		switch (command){
		case CM_META:
			tv.dpButtons.add(tv.btClose, DockPanel.WEST);
			tv.dpButtons.setCellHorizontalAlignment(tv.btClose, HasHorizontalAlignment.ALIGN_RIGHT);
			tv.btClose.addClickHandler(new ClickHandler() {
				
				@Override
				public void onClick(ClickEvent event) {
					tv.hide();
				}
			});			
			break;

		case CM_PLAY:
			if (info.containsKey("files")) {
				tv.hpSelButtons.add(tv.btSelAll);
				tv.hpSelButtons.add(tv.btUnSelAll);
				tv.dpButtons.add(tv.hpSelButtons, DockPanel.WEST);
			}
			tv.hpOpButtons.add(tv.btProperties);
			tv.hpOpButtons.add(tv.btCancel);
			tv.hpOpButtons.add(tv.btPlay);
			tv.dpButtons.add(tv.hpOpButtons, DockPanel.EAST);
			tv.dpButtons.setCellHorizontalAlignment(tv.hpOpButtons, HasHorizontalAlignment.ALIGN_RIGHT);

			tv.btProperties.addClickHandler(new ClickHandler() {
				
				@Override
				public void onClick(ClickEvent event) {
					TorrentPopupPresenter tb=new TorrentPopupPresenter(udmStatus);
					tb.loadAndBind(CM_META, rootFile);
				}
			});
			
			tv.btSelAll.addClickHandler(new ClickHandler() {
				
				@Override
				public void onClick(ClickEvent event) {
					for (int i=0; i<tv.ftFiles.getRowCount(); i++)
						((CheckBox)tv.ftFiles.getWidget(i, 0)).setValue(true);
				}
			});
			tv.btUnSelAll.addClickHandler(new ClickHandler() {
				
				@Override
				public void onClick(ClickEvent event) {
					for (int i=0; i<tv.ftFiles.getRowCount(); i++)
						((CheckBox)tv.ftFiles.getWidget(i, 0)).setValue(false);
				}
			});
			tv.btCancel.addClickHandler(new ClickHandler() {
				
				@Override
				public void onClick(ClickEvent event) {
					tv.hide();
				}
			});
			tv.btPlay.addClickHandler(new ClickHandler() {
				
				@Override
				public void onClick(ClickEvent event) {
					tv.hide();
					udmStatus.standardRequest("ctor", rootFile, "");
				}
			});
			break;
		}
		
		tv.dpButtons.setWidth("100%");
		tv.vpMain.add(tv.dpButtons);
		tv.vpMain.setSpacing(10);
		tv.add(tv.vpMain);				
		tv.center();
		tv.dpButtons.setWidth(width*0.4 + "px");
		tv.vpMain.setHorizontalAlignment(VerticalPanel.ALIGN_CENTER);
		}

	void insertKeyRow(String key, JSONObject jo) {
		if (jo.containsKey(key)) {
			if (jo.get(key).isString()!=null) insertRow(key, jo.get(key).toString());
			if (jo.get(key).isBoolean()!=null) insertRow(key, jo.get(key).toString());
			if (jo.get(key).isNumber()!=null) insertRow(key, Util.JSONNumberFormat(key, jo));
			if (jo.get(key).isArray()!=null) insertArray(key, jo.get(key).isArray());
			if (jo.get(key).isObject()!=null) insertRow(key, jo.get(key).toString());
			}
		}
	
	void insertObject(String key, JSONObject jo){
		//TODO
	}
	
	void insertArray(String key, JSONArray ja){
		int rows=ja.size();
		if (rows==0) return;
		Table avp=new Table();
		avp.resize(rows, 1);
		for(int i=0;i<rows;i++){
			if (ja.get(i).isArray()!=null)
				avp.setWidget(i,0,new Label(ja.get(i).isArray().get(0).toString().replace("\"", "")));
			else
				avp.setWidget(i,0,new Label(ja.get(i).toString().replace("\"", "")));
		}
		int i=tv.ftMain.getRowCount();
		tv.ftMain.setText(i, 0, key + ":");
		tv.ftMain.setWidget(i, 1, avp);
		tv.ftMain.getCellFormatter().setVerticalAlignment(i,0,HasVerticalAlignment.ALIGN_TOP);
		tv.ftMain.getCellFormatter().setVerticalAlignment(i,1,HasVerticalAlignment.ALIGN_TOP);
		avp.setStyleName("tableborder");
	}
	
	void insertRow(String key, String value) {
		int i=tv.ftMain.getRowCount();
		Label l=new Label(value.replace("\"", ""));
		l.setStyleName("tableborder");
		tv.ftMain.setText(i, 0, key + ":");
		tv.ftMain.setWidget(i, 1, l);
		tv.ftMain.getCellFormatter().setVerticalAlignment(i,0,HasVerticalAlignment.ALIGN_TOP);
		tv.ftMain.getCellFormatter().setVerticalAlignment(i,1,HasVerticalAlignment.ALIGN_TOP);
	}
}
